package com.xwj.juc.queue;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author xwj
 * @date 2020/3/12
 */
public class DelayQueueCache {
    private static final DelayQueue<Element<String>> queue = new DelayQueue<>();
    private static final ConcurrentHashMap<String, Object> cache = new ConcurrentHashMap(256);

    private class CheckExpireTask implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    Element element = queue.take();
                    if (element != null) {
                        System.out.println(element.getK() + "过期了");
                        cache.remove(element.getK());
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void startCheckExpireTask() {
        new Thread(new CheckExpireTask()).start();
    }

    public void put(String key, Object value, long timeout, TimeUnit unit) {
        Element<String> element = new Element<>();
        element.setK(key);
        element.setExpireTime(unit.convert(System.currentTimeMillis() + timeout, unit));
        queue.offer(element);
        cache.put(key, value);
    }

    public Object get(String key) {
        return cache.get(key);
    }

    public static void main(String[] args) throws InterruptedException {
        DelayQueueCache cache = new DelayQueueCache();
        cache.startCheckExpireTask();

        for (int i = 0; i < 5; i++) {
            cache.put("No" + i, "Value of No" + i, 1500, TimeUnit.MILLISECONDS);
            TimeUnit.MILLISECONDS.sleep(500);
        }

        for (int i = 0; i < 5; i++) {
            System.out.println(cache.get("No" + i));
        }
    }

}
